package com.oneday.nuo.base.security.auth;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;

import com.oneday.nuo.base.security.jwt.JwtUtil;
import com.oneday.nuo.base.security.user.NuoUser;
import com.oneday.nuo.base.service.NuoMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 用户登录成功
 * @Author: liushuai
 * @Date: 2021/2/19 19:31
 * @param : * @param null
 * @return :
 **/
@Component
public class NuoLoginSuccessHander implements AuthenticationSuccessHandler {
    @Autowired
    private NuoMenuService nuoMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        PrintWriter writer = null;
        NuoUser info = (NuoUser)authentication;
        //用户菜单
        Map<String, Object> menus = nuoMenuService.queryMenuByUserId(info.getId());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        try {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.addHeader("Authorization", "Bearer " + "admin");
            writer = httpServletResponse.getWriter();
            JSONObject json = new JSONObject();
            json.set("code","100");
            json.set("message","登录成功");
            JSONObject data = new JSONObject();
            data.set("userName",info.getUsername());
            data.set("realName",info.getRealName());
            json.set("data",data);
            json.set("token",info.getToken());
            json.set("menu",menus.get("menus"));
            json.set("router",menus.get("router"));
            writer.println(json.toString());
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (JSONException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            writer.close();
        }
    }


}
